// Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
// This source file is part of the Cangjie project, licensed under Apache-2.0
// with Runtime Library Exception.
//
// See https://cangjie-lang.cn/pages/LICENSE for license information.

#include "Deveco/ParseEnvironmentVariable.h"

using Platform::EnvironmentVariable;

static std::string Trim(const std::string &str)
{
    const auto first = str.find_first_not_of(" \t");
    const auto last = str.find_last_not_of(" \t");
    return (first == std::string::npos || last == std::string::npos) ? "" : str.substr(first, (last - first + 1));
}

namespace CangjieMigrator::Deveco {

std::unique_ptr<EnvironmentVariable> ParseEnvironmentVariableLog(std::string line)
{
    line = Trim(line);

    const auto colon = line.find_first_of(':');
    if (colon == std::string::npos || colon == 0) {
        return nullptr;
    }

    const auto leftQuotation = line.find_first_of('\'', colon);
    if (leftQuotation == std::string::npos) {
        return nullptr;
    }

    const auto rightQuotation = line.find_last_of('\'');
    if (rightQuotation == std::string::npos) {
        return nullptr;
    }

    if (rightQuotation == leftQuotation || rightQuotation - leftQuotation == 1) {
        return nullptr;
    }

    const auto name = line.substr(0, colon);
    const auto value = line.substr(leftQuotation + 1, rightQuotation - (leftQuotation + 1));

    return std::make_unique<EnvironmentVariable>(name, value);
}

std::vector<EnvironmentVariable> ParseEnvironmentVariableLog(std::vector<std::string> lines)
{
    auto result = std::vector<EnvironmentVariable>();
    for (const auto &line : lines) {
        const auto env = ParseEnvironmentVariableLog(line);
        if (env) {
            result.emplace_back(std::move(*env));
        }
    }
    return result;
}

} // CangjieMigrator::Deveco
